package advanced;


import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 通过javaCompiler 动态编译
 * 通过RunTime执行
 * <p>
 * 调用compiler的run方法: 其四个参数
 * in – "standard" input; use System.in if null
 * out – "standard" output; use System.out if null
 * err – "standard" error; use System.err if null
 * arguments – arguments to pass to the tool
 */
public class L_DynamicCompilation {
    public static void main(String[] args) throws Exception {
        File javaFile = new File("src/main/java/advanced/");
        //2. 通过urlClassLoader 加载类结构  反射调用
        for (File file : javaFile.listFiles()) {
            System.out.println(file);
        }
//        C:\Users\DMLYS\Documents\prepare_for_work\pfw\java_l\src\main\java\advanced\Join_L.java
        URL[] urls = {javaFile.toURL()};
        URLClassLoader loader = new URLClassLoader(urls);//路径有些异常!!!!为解决
        Class clz = loader.loadClass("HelloWorld");
        Method method = clz.getMethod("main", String[].class);
        method.invoke(null, (Object) new String[]{});//静态方法,不需要指定对象

    }

    public static void test() throws Exception {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //1. 指定动态编译的文件
        File javaFile = new File("src/main/java/advanced/Join_L.java");
        File classFile = new File("src/main/java/advanced/Join_L");
        //2. 将字符串存储为io流临时文件
        String str = "public class Hi {\n" +
                "    public static void main(String[] args) {\n" +
                "        System.out.println(\"hi, this is me\");\n" +
                "    }\n" +
                "}\n";
        System.out.println(javaFile.getPath());
        int status = compiler.run(null, null, null, javaFile.getPath());
        if (status == 0) {
            System.out.println("编译成功");
        } else {
            System.out.println("编译失败");
        }

        Runtime run = Runtime.getRuntime();

        Process process = run.exec("java -cp " + classFile + " Join_L");
        InputStream inputStream = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
}
